
package com.scs.application.modules.settlement.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.modules.settlement.dto.BillDTO;
import com.scs.application.modules.settlement.entity.Bill;
import com.scs.application.modules.settlement.request.BillQueryRequest;
import com.scs.application.modules.settlement.service.BillService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * 记账单 controller
 */
@AllArgsConstructor
@RestController
@Slf4j
@RequestMapping("/settlement/bills")
public class BillController extends CrudController<Bill, String, BillService> implements ImAndExAbleController<BillQueryRequest> {

    @PostMapping
    public CommonResult add(@RequestBody @Valid Bill entity) {
        boolean bSave = service.add(entity);
        return bSave ? CommonResult.ok("新增成功", entity) : CommonResult.error("新增失败");
    }

    @Override
    @PutMapping
    public CommonResult update(@RequestBody @Valid Bill entity) {
        boolean bUpdate = service.add(entity);
        return bUpdate ? CommonResult.ok("保存成功", entity) : CommonResult.error("保存失败");
    }

    @GetMapping("/page")
    public PageResult page(BillQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }


    @GetMapping("/list")
    public CommonResult list(BillQueryRequest request) {
        List<Bill> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }

    /**
     * 导入.txt
     */
    @PostMapping({"/getTxtDataList"})
    private CommonResult getTxtDataList(MultipartFile file)throws IOException {

        String strSettlements = new String(file.getBytes(), "UTF-8");
        try {
            List<BillDTO> billDTOS = JSON.parseArray(strSettlements, BillDTO.class);
            if (billDTOS != null && billDTOS.size() > 0) {
                service.batchSaveForFeign(billDTOS);
            }
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        return  CommonResult.ok("导入成功");
    }


}
